package pl.edu.pw.stud.ltrzaska.test;

import static org.junit.Assert.assertTrue;

import java.io.File;
import java.util.LinkedList;
import java.util.Map;

import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemException;
import org.apache.log4j.Logger;
import org.junit.Test;

import pl.edu.pw.stud.ltrzaska.exception.FilesysPolicyException;
import pl.edu.pw.stud.ltrzaska.filesystem.VirtualFsReader;
import pl.edu.pw.stud.ltrzaska.logic.FsEquivalentsFinder;
import pl.edu.pw.stud.ltrzaska.logic.FsObjectEquivalent;
import pl.edu.pw.stud.ltrzaska.logic.PolicyLoader;
import pl.edu.pw.stud.ltrzaska.logic.ValidationContext;
import pl.edu.pw.stud.ltrzaska.policy.entity.Policy;

public class CorrectnessCheckTestCase {
	private static final Logger LOGGER = Logger.getLogger(LoadPolicyTestCase.class);

	@Test
	public void checkCorrectness() {
		String curDir = System.getProperty("user.dir");

		File policyFile = new File(curDir, "/tests/poprawny/polityka-poprawny.xml");
		File fsEntry = new File(curDir, "/tests/poprawny/system_plikow_projekt");

		VirtualFsReader fsr = new VirtualFsReader(fsEntry);
		FileObject fsEntryFile;
		try {
			fsEntryFile = fsr.resolve();
			PolicyLoader pl = new PolicyLoader(policyFile);
			Policy policy = pl.getPolicy();

			FsEquivalentsFinder ftv = new FsEquivalentsFinder(policy, fsEntryFile);
			ftv.findEquivalents();
			Map<String, LinkedList<FsObjectEquivalent>> equivalents = ftv.getEquivalents();
			ValidationContext vc = new ValidationContext(policy, fsEntryFile);
			vc.run(equivalents);
			assert(vc.getViolations().size() == 0);
		} catch (FilesysPolicyException e) {
			LOGGER.error("", e);
		} catch (FileSystemException e) {
			LOGGER.error("", e);
		}
	}

	@Test
	public void checkIncorrectness() {
		String curDir = System.getProperty("user.dir");

		File policyFile = new File(curDir, "/tests/niepoprawny/polityka-niepoprawny.xml");
		File fsEntry = new File(curDir, "/tests/niepoprawny/system_plikow_projekt");

		VirtualFsReader fsr = new VirtualFsReader(fsEntry);
		FileObject fsEntryFile;
		try {
			fsEntryFile = fsr.resolve();
			PolicyLoader pl = new PolicyLoader(policyFile);
			Policy policy = pl.getPolicy();

			FsEquivalentsFinder ftv = new FsEquivalentsFinder(policy, fsEntryFile);
			ftv.findEquivalents();
			Map<String, LinkedList<FsObjectEquivalent>> equivalents = ftv.getEquivalents();
			ValidationContext vc = new ValidationContext(policy, fsEntryFile);
			vc.run(equivalents);
			
			assertTrue(vc.getViolations().size() == 3);
		} catch (FilesysPolicyException e) {
			LOGGER.error("", e);
		} catch (FileSystemException e) {
			LOGGER.error("", e);
		}
	}
}
